package com.ayz.gateway.server.grpc.connection;

import io.grpc.netty.shaded.io.netty.channel.Channel;
import lombok.Data;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName ConnectionManger
 * @Description TODO: 对于一个GRPC服务器而言,会有很多客户端想要连接我,当前ConnectionManger用于管理所有的GRPC客户端连接
 * @Author 快乐的星球
 * @Date 2023/5/19 16:34
 * @Version 1.0
 **/
@Data
public class ConnectionManger {
    /**
     * 服务端的地址
     */
    private String serverAddress;
    /**
     * 存储 connectionKey 与 Connection对象的映射关系
     *
     */
    private final ConcurrentHashMap<String,Connection> connectionMap=new ConcurrentHashMap<>(1024);

    public ConnectionManger(String serverAddress) {
        this.serverAddress = serverAddress;
    }

    public void registryConnection(String connectionKey,Connection connection){
        this.connectionMap.put(connectionKey,connection);
    }

    public void unRegistryConnection(String connectionKey){
        this.connectionMap.remove(connectionKey);
    }
    /**
     * 生成一个连接的key值
     * 默认是 "timestamp_ip_port"
     * @param clientIp
     * @param clientPort
     * @return
     */
    public static String generateConnectionKey(String clientIp,int clientPort){
        StringBuilder sb=new StringBuilder();
        sb.append(System.currentTimeMillis())
                .append("_").append(clientIp).append("_").append(clientPort);
        return sb.toString();
    }

    public static String generateAddress(String ip,int port){
        StringBuilder sb=new StringBuilder();
        sb.append(ip).append(":").append(port);
        return sb.toString();
    }
    @Data
    public static class Connection {
        /**
         * 客户端的IP地址
         */
        private String clientIp;
        /**
         * 客户端的端口号
         */
        private int clientPort;
        /**
         * 客户端的地址默认格式为 "ip:port"
         */
        private String address;
        /**
         * 连接管道Channel
         */
        private Channel channel;

        public Connection(String clientIp, int clientPort, String address) {
            this.clientIp = clientIp;
            this.clientPort = clientPort;
            this.address = address;
        }
    }
}
